from rest_framework import serializers
from users.models import User
import re


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'mobile', 'username', 'email', 'password')

        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
            },
            'username': {
                'min_length': 5,
                'max_length': 20,
            }
        }

    # 单字段验证
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机格式错误')
        return value

    # 密码加密(保存密码加密)
    def create(self, data):
        # user = super().create(validated_data)
        # user.set_password(validated_data['password'])
        # user.save()
        user = User.objects.create_user(**data)
        return user
